// src/components/composables/useCategoryEdit.ts
import { ref, reactive, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import type { UploadProps } from 'element-plus'
import myaxios from '@/auth/auth.service'
import {showToastMessage} from "@/utils/message"

// ✅ 1. 完整定义类别表单数据类型
interface CategoryForm {
  name: string;
  description: string;
  address: string;
  construction_age: string;
  // 增加 construction_type_selected 字段
  construction_type_selected: string[];
  // 增加 construction_type_other 字段，用于处理“其他”选项
  construction_type_other: string;
  layout_orientation: string;
  // 增加 protection_level_main 字段
  protection_level_main: string;
  protection_level_extra: string;
  image: any[]; // 上传组件使用的 fileList 结构
}

export function useCategoryEdit() {
  // ✅ 2. 初始化完整的 formData
  const formData = reactive({
    category: {
      name: '',
      description: '',
      address: '',
      construction_age: '',
      construction_type_selected: [], // 建筑类型初始化为数组
      construction_type_other: '',     // 建筑类型其他补充
      layout_orientation: '',
      protection_level_main: '',       // 保护级别初始化为空字符串
      protection_level_extra: '',  //保护级别补充
      image: [] as any[],
    } as CategoryForm,
  })

  // 状态管理
  const loading = ref(true)
  const error = ref('')
  const submitLoading = ref(false)
  const categoryId = ref(0)
  const currentCategory = ref<any>({})
  const formRef = ref()
  const imageChanged = ref(false)

  // 路由相关
  const route = useRoute()
  const router = useRouter()

  // 图片预览相关
  const dialogImageUrl = ref('')
  const dialogVisible = ref(false)

  // 表单验证规则（可扩展）
  const formRules = ref({
    name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
    // 可根据需要添加其他必填项校验
  })

  // 图片预览处理
  const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
    dialogImageUrl.value = uploadFile.url || ''
    dialogVisible.value = true
  }

  // 图片移除处理
  const handleRemove: UploadProps['onRemove'] = () => {
    imageChanged.value = true
  }

  // 图片变更处理
  const handleImageChange = () => {
    imageChanged.value = true
  }

  // ✅ 3. 获取类别数据并填充完整字段
  const fetchCategoryData = async () => {
    loading.value = true;
    error.value = '';

    try {
      categoryId.value = parseInt(route.params.id as string, 10);
      const response = await myaxios.fetchCategoryDetail(categoryId.value);
      console.log('Response data:', response.data); // 添加调试代码
      currentCategory.value = response.data;

      if (!currentCategory.value) {
        throw new Error('Invalid category data');
      }
      const data = currentCategory.value;
      formData.category.name = data.name || '';
      formData.category.description = data.description || '';
      formData.category.address = data.address || '';
      formData.category.construction_age = data.construction_age || '';
      formData.category.layout_orientation = data.layout_orientation || '';
      // 处理 construction_type 字段
      if (data.construction_type) {
        const items = data.construction_type.split(',').map(item => item.trim());
        formData.category.construction_type_selected = [];
        formData.category.construction_type_other = '';

        for (const item of items) {
          if (item.startsWith('其他:')) {
            // 将 "其他" 添加到选中数组
            formData.category.construction_type_selected.push('其他');
            // 提取冒号后的部分
            formData.category.construction_type_other = item.slice(3).trim(); // 去掉 "其他:" 三个字符
          } else {
            formData.category.construction_type_selected.push(item);
          }
        }
      } else {
        formData.category.construction_type_selected = [];
      }

      // 可选：去重（防止重复添加“其他”）
      formData.category.construction_type_selected = [...new Set(formData.category.construction_type_selected)];

      // 处理 protection_level 字段
      if (data.protection_level) {
        const parts = data.protection_level.split(',').map(part => part.trim());
        formData.category.protection_level_main = parts[0] || ''; // 第一部分为主级别
        formData.category.protection_level_extra = parts.length > 1 ? parts.slice(1).join(', ') : ''; // 剩余部分作为补充（防止有多个逗号）
      } else {
        formData.category.protection_level_main = '';
        formData.category.protection_level_extra = '';
      }
    } catch (e) {
      console.error('获取类别数据失败', e);
      error.value = '获取类别数据失败，请重试';
    } finally {
      loading.value = false;
    }
  }

  const handleSubmit = async () => {
    submitLoading.value = true

    try {
      await formRef.value?.validate()

      const form = new FormData()

      // 添加基本字段
      form.append('name', formData.category.name)
      form.append('description', formData.category.description || '')
      form.append('address', formData.category.address || '')
      form.append('construction_age', formData.category.construction_age || '')
      form.append('layout_orientation', formData.category.layout_orientation || '')

      // ✅ 合并 construction_type 字段
      let constructionTypes = [...formData.category.construction_type_selected];
      // 如果选择了“其他”，并且有补充内容，则替换为 "其他:xxx"
      if (constructionTypes.includes('其他')) {
        const otherValue = formData.category.construction_type_other.trim();
        if (otherValue) {
          // 移除原来的 "其他"，替换成 "其他:value"
          constructionTypes = constructionTypes.filter(t => t !== '其他');
          constructionTypes.push(`其他:${otherValue}`);
        }
      }
      form.append('construction_type', constructionTypes.join(', '));

      // ✅ 合并 protection_level 字段
      let protectionLevel = formData.category.protection_level_main || '';
      if (formData.category.protection_level_extra) {
        protectionLevel += ', ' + formData.category.protection_level_extra;
      }
      form.append('protection_level', protectionLevel);

      // 图片处理
      if (imageChanged.value) {
        if (formData.category.image.length > 0) {
          const rawFile = getRawFile(formData.category.image[0])
          if (rawFile) {
            form.append('image', rawFile)
          } else {
            showToastMessage("warning","图片文件无效")
            return
          }
        } else {
          // 可选：如果允许删除图片，可以发送空值或删除标记
          // form.append('image', '') // 或后端约定的删除方式
        }
      }

      // 调用更新接口
      await myaxios.updateCategory(categoryId.value, form)
      showToastMessage("success","文物主体更新成功")
      router.push('/pc/category')
    } catch (error) {
      console.error('提交失败:', error)
      showToastMessage("error","文物主体更新失败，请检查表单信息")
    } finally {
      submitLoading.value = false
    }
  }

  // 辅助函数：提取原始 File 对象
  const getRawFile = (fileItem: any): File | null => {
    if (!fileItem) return null
    if (fileItem.file instanceof File) return fileItem.file
    if (fileItem.raw instanceof File) return fileItem.raw
    if (fileItem instanceof File) return fileItem
    return null
  }

  // 表单校验失败处理
  const onFailed = (errorInfo: any) => {
    console.log('表单校验失败', errorInfo)
    showToastMessage("warning","请完善必填信息")
  }

  // 取消编辑 / 返回
  const handleCancel = () => {
    router.go(-1)
  }

  const onClickLeft = () => {
    router.go(-1)
  }

  const goToUser = () => {
    router.push('/personalinfo')
  }
  const goToCategory = () => {
    router.push('/category')
  }

  const goHome = () => {
    router.push('/category')
  }
  // 初始化加载
  onMounted(() => {
    fetchCategoryData()
  })

  // 暴露变量和方法
  return {
    formData,
    loading,
    error,
    submitLoading,
    categoryId,
    currentCategory,
    formRef,
    imageChanged,
    dialogImageUrl,
    dialogVisible,
    formRules,
    goHome,
    goToCategory,
    goToUser,
    handlePictureCardPreview,
    handleRemove,
    handleImageChange,
    fetchCategoryData,
    handleSubmit,
    handleCancel,
    onClickLeft,
    onFailed,
  }
}
